/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#ifndef LIB2D_OBJECTS_FRAMESET_H
#define LIB2D_OBJECTS_FRAMESET_H

#include <xml/Object.h>
#include <xml/Stream.h>
#include "ImageSimple.h"

namespace liba
{
namespace lib2d
{
namespace objects
{

class FrameSetRep : private xml::ObjectANSI
{
	struct Frame : public xml::ObjectANSI
	{
		Rect rect;
		virtual bool on_attribute( xml::Provider * prov, const std::string & name, const std::string & value );
	};

	AutoPtr< ImageSimple > image;
	std::vector< Frame > frames;
public:
	explicit FrameSetRep( const filesystem::String & name )
	{
		AutoPtr< resource::Resource > res = resource::Manager::create_resource( name );
		xml::StreamResource( res ).load( &xml::Root( this, "FrameSetData" ) );
	}
	virtual bool on_attribute( xml::Provider * prov, const std::string & name, const std::string & value );
	virtual bool on_node( xml::Provider * prov, const std::string & name );

	int get_width( unsigned frame )const
	{
		if( frame >= frames.size() )
			return 0;
		return frames[frame].rect.width;
	}
	int get_height( unsigned frame )const
	{
		if( frame >= frames.size() )
			return 0;
		return frames[frame].rect.width;
	}
	void render_frame( hard::Renderer * rend, const Vector2 & dst, unsigned frame, int alpha )
	{
		if( frame >= frames.size() )
			return;

		image->blit( rend, dst, frames[frame].rect, alpha );
	}
};

class FrameSet : public Shared< filesystem::String, FrameSetRep >
{
public:
	explicit FrameSet( const filesystem::String & name )
	{
		load_rep( name );
	}
	int get_height( unsigned frame )const
	{
		return get_rep()->get_height( frame );
	}
	int get_width( unsigned frame )const
	{
		return get_rep()->get_width( frame );
	}
	void render( hard::Renderer * rend, const Vector2 & dst, unsigned frame, int alpha = 255 )
	{
		get_rep()->render_frame( rend, dst, frame, alpha );
	}
};

} //namespace objects
} //namespace lib2d
} //namespace liba

using namespace liba;

#endif //LIB2D_OBJECTS_FRAMESET_H